require('es6-promise').polyfill()

import Vue from 'vue'
import Q from 'q'

import axios from 'axios'
import FastClick from './lib/fastclick'
import envFuncs from '@/config/base'
let env = envFuncs.getParams()
import {sync} from 'vuex-router-sync'
import store from './store'
import router from './router'
import qs from 'qs'

import bbPlugin from './lib/vue-bb-plugin'
import ddPlugin from './lib/vue-dd-plugin'
import App from './App'
import filters from './filters'

import {getRequestId, S, getQueryParams, U} from './lib/backend'

import VueScroller from 'vue-scroller'
import LoadingPlugin from 'vux/src/plugins/loading'

const localStorage = require('store')
const queryString = require('query-string')

import vuei18n from 'vue-i18n'
Vue.use(vuei18n)

Vue.use(VueScroller)
Vue.use(LoadingPlugin)

import 'mint-ui/lib/infinite-scroll/style.css'
import {InfiniteScroll} from 'mint-ui'

Vue.use(LoadingPlugin)
Vue.use(InfiniteScroll)

// console.log(FastClick)
// 实例化过滤器

Object.keys(filters).forEach(k => Vue.filter(k, filters[k]))

window.getParamByName = function (name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}

window.getNoneHashUrl = function (url) {
  // let query = url.split('?')
  // const argsStr = query.length > 1 ? query[1] : ''
  return url.split('#')[0]
}

Vue.config.debug = process.env.NODE_ENV !== 'production'
Vue.config.devtools = process.env.NODE_ENV !== 'production'

let dd = window.dd || window.DingTalkPC

const commit = store.commit || store.dispatch

let ddConfig = null
let isSignAuth = false
let siteParams

// 自动登录机制
let i = 0;
axios.interceptors.response.use((response) => {
  return Q.Promise((resolve, reject) => {
    if (typeof response.data.errcode !== 'undefined' && [100001, 100003].indexOf(response.data.errcode) > -1 && i<2) {
      getRequestAuthCode()
        .then(login)
        .then((freshtoken) => {
          if (freshtoken) {
            const config =  response.config
            config.url = response.config.url.replace(token, freshtoken);
            commit('UPDATE_TOKEN', freshtoken)
            token = freshtoken;
            resolve(axios(config));
            i ++;
          } else {
            resolve(response);
            i = 0;
          }
        })
      } else{
        resolve(response);
      }
  });
});

getConfig()
  .then(data => {
    ddConfig = data
    console.log(JSON.stringify(ddConfig))
    window['ddConfig'] = ddConfig
    let config = dd.config(ddConfig)
    console.log(config)
    return config
  })
  .catch(err => {
    console.error('getConfig', err)
  })
  .finally(() => {
    // 开发环境
    console.log('storeSiteParams isSignAuth', isSignAuth)
    if (isSignAuth === false) {
        ddIsReady().then(initVue).then(getRequestAuthCode).then(login).then(initLoginUser).then(() => {
          if (ddConfig != null) {
            commit('DDCONFIG_SUCCESS', ddConfig)
          } else {
            commit('DDCONFIG_ERROR', false)
          }
          startApp()
          console.log('init vue 完成 FastClick 加载成功 ')
        })
    } else {
      login().then(initVue).then(() => {
        startApp()
        console.log('storeSiteParams init vue 完成 FastClick 加载成功 ')
      })
    }
  })

function getConfig () {
  return Q.Promise((success, error) => {
    let url = getNoneHashUrl(document.URL)
    let storeSiteParams = localStorage.get('siteParams')
    let originSiteParams = getQueryParams()
    console.log('storeSiteParams, originSiteParams', storeSiteParams, originSiteParams)
    if (storeSiteParams && storeSiteParams.corpId === originSiteParams.corpId ) {
      if (originSiteParams.site_id === storeSiteParams.site_id) {
        siteParams = storeSiteParams
      } else {
        siteParams = originSiteParams
      }
    } else {
        siteParams = originSiteParams;
        localStorage.set('siteParams', siteParams)
    }
    console.log('siteParams', siteParams)

    let params = U(
      Object.assign(siteParams, {url: encodeURIComponent(url)})
    )
    // let query = document.URL.split('?')
    // axios.get(env.API_HOST+'/getConfig.php', {params: {paramUrl: url},timeout: 2000,}).then(function (response) {
    // if(response.status === 200 && response.data.code === 200){
    //   let res = response.data.result;
    // alert(env.CRM_API_HOST+'dd_config?'+params+'url='+url)
  let HTTP
    if (typeof siteParams['corpId'] !== 'undefined') {
      HTTP = axios.post(env.CORP_API_HOST + '/ding-isv-access/get_js_config',
        qs.stringify({corpId: siteParams['corpId'], url: url}),
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }
      )
    } else if (typeof siteParams['signature'] !== 'undefined') {
      isSignAuth = true
      return success({
        version: ''
      })
    } else {
      HTTP = axios.get(env.CRM_API_HOST + '/dd_config?' + params)
    }
    HTTP.then(function (response) {
        if (response.status === 200 && response.data.errcode === 0) {
          let res = response.data.results
          console.log(res, 'response.data.results')
          let ddConfig = {
            agentId: res.agentId, // 必填，微应用ID
            corpId: res.corpId, // 必填，企业ID
            timeStamp: res.timeStamp, // 必填，生成签名的时间戳
            nonceStr: res.nonceStr, // 必填，生成签名的随机串
            signature: res.signature, // 必填，签名
            type: 0, // 选填。0表示微应用的jsapi,1表示服务窗的jsapi。不填默认为0。该参数从dingtalk.js的0.8.3版本开始支持
            jsApiList: [
              'runtime.info',
              'runtime.permission.requestAuthCode',
              'runtime.permission.requestOperateAuthCode', // 反馈式操作临时授权码

              'biz.alipay.pay',
              'biz.contact.choose',
              'biz.contact.complexChoose',
              'biz.contact.complexPicker',
              'biz.contact.createGroup',
              'biz.customContact.choose',
              'biz.customContact.multipleChoose',
              'biz.ding.post',
              'biz.map.locate',
              'biz.map.view',
              'biz.util.openLink',
              'biz.util.open',
              'biz.util.share',
              'biz.util.ut',
              'biz.util.uploadImage',
              'biz.util.previewImage',
              'biz.util.datepicker',
              'biz.util.timepicker',
              'biz.util.datetimepicker',
              'biz.util.chosen',
              'biz.util.encrypt',
              'biz.util.decrypt',
              'biz.chat.pickConversation',
              'biz.telephone.call',
              // 'biz.navigation.setLeft',
              'biz.navigation.setTitle',
              'biz.navigation.setIcon',
              'biz.navigation.close',
              'biz.navigation.setRight',
              // 'biz.navigation.setMenu',
              'biz.user.get',

              'ui.progressBar.setColors',

              'device.base.getInterface',
              'device.connection.getNetworkType',
              'device.launcher.checkInstalledApps',
              'device.launcher.launchApp',
              'device.notification.confirm',
              'device.notification.alert',
              'device.notification.prompt',
              'device.notification.showPreloader',
              'device.notification.hidePreloader',
              'device.notification.toast',
              'device.notification.actionSheet',
              'device.notification.modal',
              'device.geolocation.get',

              'biz.contact.externalComplexPicker'
            ] // 必填，需要使用的jsapi列表，注意：不要带dd。
          }
          success(ddConfig)
        } else {
          error({errCode: -2, msg: '接口请求失败222'})
        }
      })
      .catch(function (err) {
        error({errCode: -2, msg: '接口请求失2败'})
      })
  })
}

function initMenu () {
  // if (typeof dd.biz.navigation.setMenu !== 'function') return

  // dd.biz.navigation.setMenu({
  //   backgroundColor: '#FFFFFF',
  //   textColor: '#0089cd',
  //   items: [
  //     {
  //       id: 'refresh', // 字符串
  //       text: '刷新'
  //     }
  //   ],
  //   onSuccess: function (data) {
  //     console.log(data)
  //     if (data.id === 'refresh') {
  //       location.reload()
  //     }
  //     /*
  //   {"id":"1"}
  //   */
  //   },
  //   onFail: function (err) {}
  // })
}

Vue.initMenu = initMenu

function startApp() {
  router.afterEach(({to, from, next}) => {
    Vue.initMenu()
  })

  sync(store, router)

  const app = new Vue({
    router,
    store,
    ...App
  })

  Vue.config.productionTip = false

  /* eslint-disable no-new */

  app.$mount('#app-box')
  router.beforeEach((to, from, next) => {
    commit('UPDATE_LOADING', true)
    next()
  })

  router.afterEach((to, from) => {
    const loader = document.getElementById('loader')
    if (loader) loader.remove()
    commit('UPDATE_LOADING', false)
    // next()
  })

  var deviceIsWindowsPhone =
    navigator.userAgent.indexOf('Windows Phone') >= 0
  let deviceIsAndroid =
    navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone

  if (!deviceIsAndroid) {
    FastClick.attach(document.body)
  }

}

function ddIsReady () {
  return Q.Promise((success, error) => {
    let timeout = setTimeout(() => {
      error({errCode: -1, msg: 'dd.ready初始化超时'})
    }, 2000)

    dd.ready(function (e) {
      console.log('初始化钉钉')
      clearTimeout(timeout)
      console.debug('test')
      success(true)
    })

    dd.error(function (err) {
      console.log(err)
      clearTimeout(timeout)
      let siteParams = getQueryParams()
      const errorParam = JSON.stringify(err, Object.getOwnPropertyNames(err))

      let times = siteParams['times'] ? 1 : 0;
      console.log('times', siteParams['times'])
      if (times < 1) {
        let url = new URL(document.URL);
        let params = new URLSearchParams(url.search.slice(1))
        params.append('times', ++times);
        url.search = '?' + params.toString();
        let redirectUrl  = url.toString();
        axios.post(env.CRM_API_HOST + '/refresh_ticket', {error: errorParam, site_id: siteParams.site_id})
          .then((response) => {
            location.href = redirectUrl;
          })
      }
      
      /**
       {
        message:"错误信息",//message信息会展示出钉钉服务端生成签名使用的参数，请和您生成签名的参数作对比，找出错误的参数
        errorCode:"错误码"
       }
       **/
      console.error('dd error: ', err.message, err, ddConfig, document.URL)

      error({errCode: -1, msg: 'dd.error配置信息不对'})
    })
  })
}

// 获取请求授权码
function getRequestAuthCode () {
  return Q.Promise((success, error) => {
    dd.runtime.permission.requestAuthCode({
      corpId: ddConfig.corpId,
      onSuccess: function (result) {
        ddConfig.authCode = result.code
        console.log(ddConfig.authCode, 'ddConfig.authCode')
        success()
      },
      onFail: function (err) {
        console.error(
          JSON.stringify(err),
          'failed',
          'ddConfig.corpId:' + ddConfig.corpId
        )
        error({errCode: -1, msg: 'dd.error配置信息不对'})
      }
    })
  })
}

function login () {
  return Q.Promise((success, error) => {
    console.log(ddConfig.authCode, 'ddConfig.authCode ')
    let paramsArgs = siteParams ? siteParams : getQueryParams()
    let params = S({
      trace: {
        requestId: getRequestId()
      },
      info: {
        code: ddConfig.authCode
      }
    })
    paramsArgs['code'] = ddConfig.authCode
    let queryArgs = U(paramsArgs)
    // if(paramsArgs['debug']) alert(queryArgs)
    commit('UPDATE_SITE_ID', paramsArgs['site_id'])
    let LOGIN_URL
    if (typeof paramsArgs['corpId'] !== 'undefined') {
      LOGIN_URL = env.CORP_API_HOST + '/ding-isv-access/getScrmUserByByAuthCode?'
    } else if (typeof paramsArgs['signature'] !== 'undefined') {
      LOGIN_URL = env.CRM_API_HOST + '/sign'
      queryArgs = '';
      params = params = S({
        trace: {
          requestId: getRequestId()
        },
        info: paramsArgs
      })
    } else {
      LOGIN_URL = env.CRM_API_HOST + '/ding/login?'
    }
    axios
      .post(LOGIN_URL + queryArgs, params)
      .then(function (response) {
        if (response.status === 200 && response.data.errcode === 0) {
          let res = response.data.results
          commit('UPDATE_TOKEN', res.token)
          success(res.token)
        } else {
          alert(response.data.errmsg)
          localStorage.remove('siteParams')
          error({errCode: -2, msg: '接口请求失2败'})
        }
      })
      .catch(function (err) {
        console.error(err)
        localStorage.remove('siteParams')
        error({errCode: -2, msg: '接口请求失2败'})
      })
  })
}

function initLoginUser (token) {
  return Q.Promise((success, error) => {
    let params = U(getQueryParams())
    axios
      .get(env.CRM_API_HOST + '/users/' + token + '?' + params)
      .then(function (response) {
        if (response.status === 200 && response.data.errcode === 0) {
          let res = response.data.results
          if (typeof res['site_id'] !== 'undefined') {
            commit('UPDATE_SITE_ID', res['site_id'])
          }
          commit('UPDATE_USER', res)
          success()
        } else {
          error({errCode: -2, msg: '接口请求失2败'})
        }
      })
      .catch(function (err) {
        console.error(err)
        error({errCode: -2, msg: '接口请求失2败'})
      })
  })
}

function initVue () {
  return Q.Promise((success, error) => {
    Vue.use(bbPlugin)
    Vue.use(ddPlugin)
    success()
  }).catch(function (err) {
    console.log(err, 2)
  })
}
